package com.brossdong.socket.netty.chaibao;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * Created by brossdong on 2018/2/22.
 */
public class Server {

    public static void main(String[] args) throws Exception {
        //创建两个线程
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        //创建一个辅助类
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workGroup)
         .channel(NioServerSocketChannel.class)
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             protected void initChannel(SocketChannel sc) throws Exception {
                 //设置特殊分隔符
                 ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
                 //第二种  设置定长
                 //sc.pipeline().addLast(new FixedLengthFrameDecoder(5))
                 sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));
                 //设置字符串形式解码
                 sc.pipeline().addLast(new StringDecoder());

                 sc.pipeline().addLast(new ServerHandler());
             }
         });

        //绑定连接
        ChannelFuture future = b.bind(8765).sync();

        //关闭
        future.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();

    }

}
